//
//  OAuthController.swift
//  Weibo项目
//
//  Created by vn on 16/7/20.
//  Copyright © 2016年 vn. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthController: UIViewController,UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
    
        setUpUI()
        
    }
    
    override func loadView() {
        
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        
        
        let url = NSURL(string: urlString)
        
        guard let u = url else{
            
            return
        }
        
        let request = NSURLRequest(URL:u)
        webView.loadRequest(request)
        
        webView.delegate = self;
        
        view = webView
        
    }
    
    
    
    //webView代理方法
    //开始加载时候
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    //加载结束
    func webViewDidFinishLoad(webView: UIWebView) {
        
       SVProgressHUD.dismiss()
    }
    
    //加载错误
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        print(error)
        
    }
    
    
      /*
    监听webView 将要加载的request
    - 其有返回值
    - 如果返回为true 代表继续加载
    - 如果返回为false 带包要停止加载
    - 默认如果不实现该方法 默认为true
    
    */

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //减加载的请求转换成字符串
        let requestStr = request.URL?.absoluteString
        
        //判断是否为空,而且前缀等于我们的回调Url
        if let rel = requestStr where(rel.hasPrefix(APPREDIRECT_URI)){
            
            
            //拿到请求参数
            let q = request.URL?.query
            
            if let qurey = q{
                
                //拿到code码,请求access_token;
                let code = qurey.substringFromIndex("code=".endIndex)
                //viewModel请求回调,告知控制器成功与否
                OAuthViewModel.sharedViewModel.loadUesrAccount(code, isSuccess: { (isSucc) -> () in
                    
                        if !isSucc {
                        print("请求失败")
                        return
                    }
                    
                    // 先关闭当前界面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        // 发送一个通知 告知appdelegate 切换根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVC, object: nil)
                    })
                    
                    
                    
                })
                
                return false
                
                
            }
        }
       
        return true
    }
    
    //自动填充监听方法
    func fillClick(){
        
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)

    }
    
    //设置导航栏button
    func setUpUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消", style: UIBarButtonItemStyle.Plain, target: self, action:"cancelClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title:"点击填充", style: UIBarButtonItemStyle.Plain, target: self, action:"fillClick")
        
    }
    
    //监听方法
    func cancelClick(){
        
       navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //lazy webView
     lazy var webView:UIWebView = UIWebView()
    
   
}
